package com.thesis.manage.common.mongodb.config;


import com.thesis.manage.common.entity.AbstractMongoEntity;
import com.thesis.manage.common.entity.Sequence;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author php
 * @date 2017/11/28
 * mongodb id自增
 */
@Component
public class SaveEventListener extends AbstractMongoEventListener<AbstractMongoEntity> {
    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public void onBeforeConvert(BeforeConvertEvent event) {
        if (event != null) {
            AbstractMongoEntity source = (AbstractMongoEntity) event.getSource();
            if (source.getId() == null) {
                source.setId(getNextId(source.getClass().getSimpleName()));
            }
        }
    }


    /**
     * 获取自增id
     *
     * @param collName collName
     * @return long
     */
    private Long getNextId(String collName) {
        Query query = new Query(Criteria.where("collName").is(collName));
        Update update = new Update();
        update.inc("seqId", 1);
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.upsert(true);
        options.returnNew(true);
        Sequence seqId = this.mongoTemplate.findAndModify(query, update, options, Sequence.class);
        return seqId.getSeqId();
    }

}
